package cn.xeblog.server.action.timer;

import lombok.Getter;

public class TokenBucket {
    @Getter
    private final String bucketId;
    private final int maxCapacity;
    private final double tokensPerSecond;
    private double tokens;
    private long lastRefillTime;

    public TokenBucket(String bucketId) {
        this.bucketId = bucketId;
        this.lastRefillTime = System.currentTimeMillis();

        this.maxCapacity = 10;
        this.tokensPerSecond = 0.3;
        this.tokens = maxCapacity * 0.4;
    }

    public TokenBucket(String bucketId, int maxCapacity, double tokensPerSecond, double initRate) {
        this.bucketId = bucketId;
        this.maxCapacity = maxCapacity;
        this.tokensPerSecond = tokensPerSecond;
        this.tokens = maxCapacity * initRate;
        this.lastRefillTime = System.currentTimeMillis();
    }

    public synchronized void refillTokens() {
        long currentTime = System.currentTimeMillis();
        long elapsedMillis = currentTime - lastRefillTime;
        double newTokens = elapsedMillis * tokensPerSecond / 1000;
        tokens = Math.min(maxCapacity, tokens + newTokens);
        lastRefillTime = currentTime;
    }

    public synchronized boolean getAndConsumeToken() {
        if (tokens >= 1) {
            tokens--;
            lastRefillTime = System.currentTimeMillis();
            return true;
        }
        return false;
    }

}
